package com.vip.iot.protocol.http;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.NameValuePair;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * 基础URL和参数集合的拼接，发送和接收响应数据
 *
 * @author wgb
 * @Date 2019/3/5
 */
public class HttpClient {
    /**
     * 发送拼接过的URL和接收响应数据
     *
     * @param url 基础URL
     * @param m   参数集合
     * @return
     */
    public static String MethodPostResponse(String url, Map<String, String> m) {
        String ret = "";
        HttpProtocolHandler httpProtocolHandler = HttpProtocolHandler.getInstance();
        /* Post传递变量必须用NameValuePair[]数组 */
        NameValuePair[] params = generatNameValuePair(m);
        HttpRequest request = new HttpRequest(HttpResultType.BYTES);
        request.setCharset("UTF-8");
        request.setParameters(params);
        request.setUrl(url);
        HttpResponse response = httpProtocolHandler.execute(request);
        Header[] headers = response.getResponseHeaders();
        if (response == null) {
            return "{'status':'2'}";
        }
        try {
            ret = response.getStringResult();
        } catch (UnsupportedEncodingException e) {
            System.err.println();
            e.getMessage();
            ret = "{'status':'0'}";
        }
        return ret;
    }

    public static Map<String, String> MethodPostResponse(String url, Map<String, String> m, String cookie) {
        Map<String, String> result = new HashMap<>();
        String ret = "";
        HttpProtocolHandler httpProtocolHandler = HttpProtocolHandler.getInstance();
        /* Post传递变量必须用NameValuePair[]数组 */
        NameValuePair[] params = generatNameValuePair(m);
        HttpRequest request = new HttpRequest(HttpResultType.BYTES);
        request.setCharset("UTF-8");
        request.setParameters(params);
        request.setUrl(url);
        request.setCookie(cookie);
        HttpResponse response = httpProtocolHandler.execute(request);
        Header[] headers = response.getResponseHeaders();
        Map<String, String> CookieContiner = new HashMap<>();
        for (int i = 0; i < headers.length; i++) {
            String cookieResponse = headers[i].getValue();
            String[] cookievalues = cookieResponse.split(";");
            for (int j = 0; j < cookievalues.length; j++) {
                String[] keyPair = cookievalues[j].split("=");
                String key = keyPair[0].trim();
                String value = keyPair.length > 1 ? keyPair[1].trim() : "";
                CookieContiner.put(key, value);
            }
        }
        if (response == null) {
            result.put("ret", "{'status':'2'}");
            return result;
        }
        try {
            ret = response.getStringResult();
            result.put("ret", ret);
            result.put("cookie", CookieContiner.get("PHPSESSID"));
        } catch (UnsupportedEncodingException e) {
            System.err.println();
            e.getMessage();
            ret = "{'status':'0'}";
            result.put("ret", ret);
        }
        return result;
    }

    /**
     * MAP类型数组转换成NameValuePair类型
     *
     * @param properties MAP类型数组
     * @return NameValuePair类型数组
     */
    private static NameValuePair[] generatNameValuePair(Map<String, String> properties) {
        NameValuePair[] nameValuePair = new NameValuePair[properties.size()];
        int i = 0;
        for (Map.Entry<String, String> entry : properties.entrySet()) {
            nameValuePair[i++] = new NameValuePair(entry.getKey(), entry.getValue());
        }
        return nameValuePair;
    }


}
